package com.atguigu.gmall.common.util;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author:ahang
 * @create:2022-10-04 23:38
 * @Description:
 */
@Slf4j
public class Jsons {
    //防止每次调用该方法不断new对象浪费运行内存
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转成json字符串
     * @param object
     * @return
     */
    public static String tostr(Object object){

        String json = null;
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.info("json转换异常>{}",e);
        }
        return json;
    }

    /**
     * 将字符串转换成对象
     * @param jsonStr
     * @param tf
     * @param <T>
     * @return
     */
    public static<T> T toObject(String jsonStr, TypeReference<T> tf){
        if(RedisConst.TEMP_DATA.equals(jsonStr)){
            return null;
        }
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return t;
    }

    public static<T> T toObject(String jsonStr, Class<T> tf){
        if(RedisConst.TEMP_DATA.equals(jsonStr)){
            throw new GmallException(ResultCodeEnum.DATA_NOT_EXIST);

        }
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return t;
    }
}
